package com.desire.service.purchase.impl;

import com.desire.bean.purchase.Inquiry;
import com.desire.bean.purchase.InquiryProduct;
import com.desire.common.Base.BaseServiceImpl;
import com.desire.mapper.purchase.InquiryDetailMapper;
import com.desire.mapper.purchase.InquiryMapper;
import com.desire.mapper.purchase.InquiryProductMapper;
import com.desire.service.purchase.InquiryService;
import com.desire.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author LittleDesire
 * @description
 * @date 2022-05-23 周一 21:45
 * @since 17
 */
@Service
public class InquiryServiceImpl extends BaseServiceImpl<Inquiry, InquiryMapper> implements InquiryService {
    final String PREFIX = "XJD";
    @Autowired
    InquiryDetailMapper inquiryDetailMapper;
    @Autowired
    InquiryProductMapper inquiryProductMapper;

    @Override
    @Transactional
    public int save(Inquiry mapOrEntity) {
        String id = UUID.randomUUID().toString();
        mapOrEntity.setCode(generateApplyCode(mapOrEntity.getEuid()));
        mapOrEntity.setId(id);
        // 保存询价单
        int rs = mapper.save(mapOrEntity);
        if (rs == 0) {
            return rs;
        }
        // 保存询价产品
        InquiryProduct product = mapOrEntity.getProduct();
        product.setInquiryId(id);
        rs = inquiryProductMapper.save(mapOrEntity.getProduct());

        // 保存询价明细
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("detail", mapOrEntity.getDetail());
        rs = inquiryDetailMapper.batchSave(map);

        return rs;
    }

    /**
     * 生成采购申请单号  按年归零
     *
     * @param euid 所属企业用户id
     * @return 最新的申请单编号
     */
    String generateApplyCode(String euid) {
        // 查询当前企业用户， 当年最大的编号
        String ym = DateUtils.getYearMonth();
        String code = mapper.queryMaxCode(euid, ym);
        if (null == code) {
            // 是当前年的第一个申请单编号
            return PREFIX + ym + "0001";
        }
        // 在最大的申请单编号处理后加1获得新的申请单编号
        return getNextCode(code);
    }

    /**
     * 获得当前最大编号的下一个编号
     *
     * @param code
     * @return
     */
    String getNextCode(String code) {
        String pre = code.substring(0, 11);
        String seq = code.substring(11);
        int i = Integer.parseInt(seq);
        i++;
        return pre + String.format("%04d", i);
    }
}
